<?php
    class OptionsModel
    {
        private $db;
        
        public function __construct() {
            $this->db = db::getInstance();
        }        
        
        // Get a single option
        public function getOption($id) {
            if(!empty($id)) {                
                $result = $this->db->select('*', 'options', array('where'=>array('id'=>$id)));
                return mysql_fetch_assoc($result);
            }
        }
        
        // Get a list of categories
        public function getCategories() {
            $categories = array();
            $result = $this->db->select('id,name', 'categories', array('orderby'=>'name'));            
            while($category = mysql_fetch_assoc($result)) {
                array_push($categories, array('id'=>$category['id'], 'name'=>$category['name']));
            }
            return $categories;
        }
        
        // Delete an option and the records where it holds a reference to
        public function deleteOption($id) {
            if(!empty($id)) {
                $this->db->delete('options', array('id'=>$id));
                $this->db->delete('datatype_option', array('id_option'=>$id));
                $this->db->delete('values', array('id_option'=>$id));
            }
        }
        
        // Add an option to the database
        public function addOption($values) {
            $this->db->insert('options', $values);
        }
        
        // Update an option in the database
        public function updateOption($id, $values) {
            $this->db->update('options', $values, array('id'=>$id));
        }
        
        /**
         * Get a list of all the records
         *
         * @return unknown	Array with the records
         */
        public function getRecords() {
            $records = array();
            $result = $this->db->select('*', 'options', array('orderby'=>'name'));
			while($record = mysql_fetch_assoc($result)) {
                if($record['type']=='category') {
                    $record['value'] = $this->db->get('name', 'categories', array('id'=>$record['value']));
				} 
                array_push($records, $record);
            }
            return $records;
        }
        
        /**
         * Return a list of all the available option types
         *
         * @return unknown	Array with the types
         */
        public function getTypes() {
        	$types = array(
                'text'=>'text',
                'email'=>'e-mail address',
                'url'=>'url',
                'textarea'=>'textarea',
                'category'=>'category'
            );
            return $types;
        }
    }
?>